<template>
  <view>
    <!-- 签署流量包 -->
    <uni-card :is-shadow="false" v-for="(item,index) in dataList" :key="index" class="card-list">
      <p><span class="grid-title">{{ item.name }}</span></p>
      <p style="margin:25rpx 0;">
        <span class="grid-nowPrice">¥{{ item.nowPrice }}</span>
        <span class="grid-integral" style="margin-left: 6rpx;">签署价：{{ item.unitPrice }}元/次</span>
      </p>
      <p>
        <span class="grid-oldPrice" style="color: #f56c6c;">
          原价 ¥ {{ item.oldPrice }}（节省 ¥ {{ item.oldPrice - item.nowPrice }}元）
        </span>
      </p>
      <p style="margin-top:10rpx;">
        <span class="grid-integral">签署量：{{ item.signNum }} 次 + 赠送：{{ item.giveSignNum }}次</span>
      </p>
      <p style="margin-top:5rpx;">
		<span class="grid-integral">
			分享 {{ item.shareNum }} 个企业客户可兑换，签署套餐有效期：
			<template v-for="(dictItem, index) in dicts.ec_sign_flow_fee_valid_period">
			  <template v-if="item.validPeriod == dictItem.value">
			    <span>{{ dictItem.text }}</span>
			  </template>
			</template>
		</span>			
      </p>
      <view slot="actions" class="card-actions" style="width:70%;margin:0 auto">
        <view class="card-actions-item" @click="toShowIntegralExchange(item)">
          <text class="card-actions-item-text themeColor">碳能量兑换</text>
        </view>
        <view class="card-actions-item" @click="toShowAccountBuy(item,index)">
          <text class="card-actions-item-text themeColor">余额购买</text>
        </view>
      </view>
    </uni-card>
    <!-- 个人签署套餐定制 -->
    <uni-card :is-shadow="false">
      <p><span class="grid-title">个人签署套餐定制</span></p>
      <p style="margin:25rpx;">若您签署量较大，请联系励氪签工作人员，为您定制专属合作方案。</p>
      <view class="gride-btn">
        <span>销售热线：400-891-3655</span>
        <button size="mini" class="solid_btn" @click="phone">立即联系</button>
      </view>
    </uni-card>

    <!-- 碳能量兑换 -->
    <uni-popup ref="integralPopup" type="dialog">
      <uni-popup-dialog
          :type="msgType"
          :before-close="true"
          cancelText="取消"
          confirmText="兑换"
          title="碳能量兑换"
          @confirm="toIntegralExchange"
          @close="dialogClose">
        <template v-slot="content">
          <view class="bg_title">
            购买账户【<span style="font-weight:600;">{{ companyInfo.name }}</span>】，个人账户碳能量：
            <span style="font-weight:600;">{{ integral }}</span>
            <span style="margin-left: 5rpx;">g</span>
          </view>
          <uni-forms ref="integralForm" :modelValue="form" :rules="rules" label-width="160rpx"
                     type="line">
            <uni-forms-item label="套餐名称" name="name">
              <uni-easyinput v-model="form.name" type="text" disabled/>
            </uni-forms-item>
            <uni-forms-item label="签署量" name="signNum">
              <uni-easyinput v-model="form.signNum+'次'" type="text" disabled/>
            </uni-forms-item>
            <uni-forms-item label="赠送" name="giveSignNum">
              <uni-easyinput v-model="form.giveSignNum+'次'" type="text" disabled/>
            </uni-forms-item>
            <uni-forms-item label="支付碳能量" name="integral">
              <uni-easyinput v-model="form.integral+'g'" type="text" disabled/>
            </uni-forms-item>
            <uni-forms-item label="支付密码" name="payPwd" required>
              <uni-easyinput v-model="form.payPwd" type="password" placeholder="请输入支付密码"/>
            </uni-forms-item>
            <checkbox-group @change="checkboxChange">
              <label>
                <checkbox value="1" style="transform:scale(0.6)" color="#00a660"/>
                <span class="xieyi-text">我已阅读并同意<a class="a-primary" @click.stop="toAgreement">《电子签服务购买协议》</a></span>
              </label>
            </checkbox-group>
            <p class="remind">
              <i class="iconfont" style="font-size:22rpx">&#xe70f;</i>
              <span style="margin-left:6rpx;">
								提醒：您通过个人账户碳能量兑换的签署量，将计入【
                <span style="font-weight:600;">{{ companyInfo.name }}</span>
								】企业账户，请知悉！
              </span>
            </p>
          </uni-forms>
        </template>
      </uni-popup-dialog>
    </uni-popup>

    <!-- 立即购买 -->
    <uni-popup ref="orderPopup" type="dialog">
      <uni-popup-dialog
          :type="msgType"
          :before-close="true"
          cancelText="取消"
          confirmText="确定"
          title="账户余额购买"
          @confirm="toAccountBuy"
          @close="dialogClose">
        <template v-slot="content">
          <view class="bg_title">
            企业账户【<span style="font-weight:600;">{{ companyInfo.name }}</span>】，账户余额：
            <span style="font-weight:600;">{{ companyInfo.balance }}</span>
            <span style="margin-left: 5rpx;">元</span>
          </view>
          <uni-forms ref="form" :modelValue="form" :rules="rules" label-width="150rpx" type="line">
            <uni-forms-item label="套餐名称" name="name">
              <uni-easyinput v-model="form.name" type="text" disabled/>
            </uni-forms-item>
            <uni-forms-item label="签署量" name="signNum">
              <uni-easyinput v-model="form.signNum+'次'" type="text" disabled/>
            </uni-forms-item>
            <uni-forms-item label="赠送" name="giveSignNum">
              <uni-easyinput v-model="form.giveSignNum+'次'" type="text" disabled/>
            </uni-forms-item>
            <uni-forms-item label="支付金额" name="nowPrice">
              <uni-easyinput v-model="form.nowPrice+'元'" type="text" disabled/>
            </uni-forms-item>
            <uni-forms-item label="支付人员" name="payerInfo" v-if="!canPayOrder.status" required>
              <uni-easyinput v-model="form.payerInfo" placeholder="请选择代支付人员" suffixIcon="search"
                             @iconClick="toSelectStaff"/>
            </uni-forms-item>
            <uni-forms-item label="支付密码" name="payPwd" required>
              <uni-easyinput v-model="form.payPwd" type="password" placeholder="请输入支付密码"/>
            </uni-forms-item>
            <checkbox-group @change="checkboxChange">
              <label>
                <checkbox value="1" style="transform:scale(0.6)" color="#00a660"/>
                <span class="xieyi-text">我已阅读并同意<a class="a-primary" @click.stop="toAgreement">《电子签服务购买协议》</a></span>
              </label>
            </checkbox-group>
            <p class="remind">
              <i class="iconfont" style="font-size:22rpx">&#xe70f;</i>
              <span style="margin-left:6rpx;">
								提醒：您通过企业账户余额购买的签署量，将计入【 <span style="font-weight:600;">{{ companyInfo.name }}</span>
								】企业账户，请知悉！
              </span>
            </p>
          </uni-forms>
        </template>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>
<script>
import {getDictsByNameForUni} from "@/utils/dicts";
import {accountBuy, getProductIndex, getSignFlowFeeList, integralExchange} from "@/api/ec/console/fee/product";
import {canPayOrder} from "@/api/ec/console/busiConfig/companyPayStaff";
import {getCompany} from "@/api/ec/work/company/company";

export default {
  name: 'signFlowFee',
  data() {
    return {
      // 字典查询
      dicts: {
        ec_sign_flow_fee_valid_period: [],
      },
      // 企业信息
      companyInfo: this.$store.getters.companyInfo,
      // 数据列表
      dataList: [],
      // 个人碳能量
      integral: 0,
      // 个人合同签署量
      remainingNum: 0,
      // ===============================================================================================================
      // ==== 弹出框
      // ===============================================================================================================
      msgType: 'info',
      // 电子签购买协议
      eleBuyAgreement: undefined,
      // 表单参数
      form: {
        id: undefined,
        name: undefined,
        signNum: undefined,
        integral: undefined,
        payer: undefined,
        payerMobile: undefined,
        payerId: undefined,
        payerInfo: undefined,
        payPwd: undefined,
      },
      rules: {
        payPwd: {
          rules: [
            {required: true, errorMessage: '请输入支付密码'},
          ]
        },
        payerInfo: {
          rules: [
            {required: true, errorMessage: '请选择代支付人'},
          ]
        },
      },
      // 用户是否可以直接支付
      canPayOrder: {},
    }
  },
  created() {
    this.getDicts()
    this.getCompanyInfo();
    this.getList();
    this.getIndex();
  },
  methods: {
    // ===============================================================================================================
    // ==== 加载数据字典
    // ===============================================================================================================
    /**加载数据字典*/
    getDicts() {
      // 签署套餐有效期
      this.dicts.ec_sign_flow_fee_valid_period = getDictsByNameForUni("ec_sign_flow_fee_valid_period");
    },
    /** 绑定 */
    bindingRefreshData() {
      uni.$on("signFlowFeePayInfo", (option) => {
        this.form.payerId = option.id;
        this.form.payer = option.name;
        this.form.payerMobile = option.mobile;
        this.form.payerInfo = (!!this.form.payerId) ? this.form.payer + '(' + this.form.payerMobile + ')' : "";
      })
    },
    /** 解除绑定 */
    unbindingRefreshData() {
      uni.$off('signFlowFeePayInfo');
    },
    // ===============================================================================================================
    // ==== 加载页面数据
    // ===============================================================================================================
    /** 查询企业信息 */
    getCompanyInfo() {
      this.$modal.loading();
      getCompany(this.companyInfo.id).then(response => {
        uni.hideLoading()
        this.companyInfo = response.data;
      }).catch(() => {
        uni.hideLoading()
      });
    },
    /** 查询签署流量包订单列表 */
    getList() {
      getSignFlowFeeList().then(response => {
        this.dataList = response.data;
      });
    },
    /** 产品购买 首页账户信息 */
    getIndex() {
      getProductIndex().then(response => {
        this.integral = response.data.integral;
        this.remainingNum = response.data.remainingNum;
      });
    },
    /** 电子签服务购买协议 首页账户信息 */
    toAgreement() {
      // 关掉弹出层之后再跳转
      this.dialogClose()
      this.$tab.navigateTo('/pages/common/policy/eleBuyAgreement')
    },
    /** 电子签服务购买协议 选中 */
    checkboxChange(e) {
      this.eleBuyAgreement = e.detail.value[0]
    },
    // ===============================================================================================================
    // ==== 弹出框
    // ===============================================================================================================
    /** 关闭弹出层 */
    dialogClose() {
      this.$refs.orderPopup.close()
      this.$refs.integralPopup.close()
    },
    /** 碳能量兑换 */
    toShowIntegralExchange(item) {
      this.eleBuyAgreement = undefined
      this.form = item
      this.$refs.integralPopup.open()
    },
    /** 碳能量兑换 */
    toIntegralExchange() {
      this.$refs.integralForm.validate().then((res) => {
        if (this.eleBuyAgreement != "1") {
          this.$modal.msgError("请先阅读并勾选同意《电子签服务购买协议》")
          return;
        }
        this.$modal.loading();
        integralExchange(this.form.id, this.form.payPwd).then(() => {
          this.$refs.integralPopup.close()
          uni.hideLoading()
          this.$modal.msgSuccess("兑换成功")
        }).catch(() => {
          uni.hideLoading()
        });
      });
    },
    /** 选择代支付人 */
    toSelectStaff() {
      this.$tab.navigateTo('/pages/mine/work/product/selectPayerStaff')
    },
    /** 立即购买 */
    toShowAccountBuy(item) {
      this.eleBuyAgreement = undefined
      const data = {amount: item.nowPrice};
      // 用户是否可以直接支付
      canPayOrder(data).then(response => {
        this.canPayOrder = response.data;
        if (null != this.canPayOrder) {
          this.getCompanyInfo();
          this.form.id = item.id;
          this.form.name = item.name;
          this.form.signNum = item.signNum;
          this.form.giveSignNum = item.giveSignNum;
          this.form.nowPrice = item.nowPrice;
          this.form.payerId = undefined;
          this.form.payerMobile = undefined;
          this.form.payer = undefined;
          this.form.payPwd = "";
          this.form.payerInfo = "";
          this.$refs.orderPopup.open()
        }
      });
    },
    toAccountBuy() {
      this.$refs.form.validate().then(valid => {
        if (valid) {
          if (this.eleBuyAgreement != "1") {
            this.$modal.msgError("请先阅读并勾选同意《电子签服务购买协议》")
            return;
          }
          this.$modal.loading();
          accountBuy(this.form.id, this.form.payPwd, this.form.payerId).then(() => {
            this.$refs.orderPopup.close()
            uni.hideLoading()
            this.$modal.msgSuccess("操作成功")
          }).catch(() => {
            uni.hideLoading()
          });
        }
      });
    },
    /** 立即联系 */
    phone() {
      uni.makePhoneCall({
        phoneNumber: '400-891-3655'
      });
    },
  }
}
</script>

<style lang="scss" scoped>
.remind {
  color: #666;
  font-size: 24rpx;
  margin-top: 16rpx;
}

.xieyi-text {
  font-size: 26rpx;
}

::v-deep .uni-forms-item .is-required {
  display: none;
}

.card-list {
  text-align: center;
  padding: 10rpx 20rpx !important;
}

page {
  background: $uni-bg-color-grey;
}

::v-deep .uni-popup .uni-popup__wrapper {
  width: 90% !important;
}

::v-deep .uni-popup-dialog {
  width: 100%;
}

::v-deep .content-clear-icon {
  color: $uni-color-primary !important;
}

::v-deep .uni-input-input {
  color: #666666;
  opacity: 1;
  -webkit-opacity: 1;
  -webkit-text-fill-color: #666666; // ios 和 安卓9.0 必须添加此属性，才会生效
}

::v-deep .uni-forms-item {
  margin-bottom: 22rpx;
}

::v-deep .uni-dialog-content {
  display: block;
  padding: 15px;
}

.bg_title {
  background: #f0f9eb;
  color: #555b65;
  padding: 20rpx;
  display: block;
  margin-bottom: 20rpx;
  font-size: 24rpx;
  font-weight: 400;
}

.gride-btn {
  margin-top: 30rpx;
  display: flex;
  justify-content: space-between;
}
</style>
